package com.gh.mp.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gh.mp.eduservice.entity.EduSubject;
import com.gh.mp.edu.exception.EduException;
import com.gh.mp.eduservice.mapper.EduSubjectMapper;
import com.gh.mp.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gh.mp.eduservice.entity.vo.SubjectNestedVo;
import com.gh.mp.eduservice.entity.vo.SubjectVo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Eric
 * @since 2021-04-19
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public List<String> importExcelSubject(MultipartFile multipartFile) {
        try {
            //获取输入流对象
            InputStream is = multipartFile.getInputStream();
            //创建workbook
            Workbook workbook = new HSSFWorkbook(is);
            //根据workbook获取sheet
            Sheet sheet = workbook.getSheetAt(0);

            List<String> msg = new ArrayList<>();//为了存储错误信息
            //根据sheet获取row
            int lastRowNum = sheet.getLastRowNum();
            for (int i = 1; i <= lastRowNum; i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    String str = "表格数据为空";
                    msg.add(str);
                    continue;
                }
                Cell cellOne = row.getCell(0);
                if (cellOne == null) {
                    String str = "第" + i + "行数据为空";
                    msg.add(str);
                    continue;
                }
                String value = cellOne.getStringCellValue();
                EduSubject eduSubject = this.existOneSubject(value);
                String idParent = null;
                //存储一级分类id
                if (eduSubject == null) {
                    EduSubject eduSubject1 = new EduSubject();
                    eduSubject1.setTitle(value);
                    eduSubject1.setSort(0);
                    eduSubject1.setParentId("0");
                    eduSubject1.setId(UUID.randomUUID().toString());
                    baseMapper.insert(eduSubject1);
                    idParent = eduSubject1.getId();
                } else {
                    //存在,不添加
                    idParent = eduSubject.getId();
                }
                Cell cellTwo = row.getCell(1);
                if (cellTwo == null) {
                    String str = "第" + i + "行数据为空";
                    msg.add(str);
                    continue;
                }
                String valueTwo = cellTwo.getStringCellValue();
                EduSubject existTwoSubject = this.existTwoSubject(valueTwo, idParent);
                if (existTwoSubject == null) {
                    EduSubject eduSubject1 = new EduSubject();
                    eduSubject1.setTitle(valueTwo);
                    eduSubject1.setSort(0);
                    eduSubject1.setParentId(idParent);
                    eduSubject1.setId(UUID.randomUUID().toString());
                    baseMapper.insert(eduSubject1);
                }
            }
            return msg;
        } catch (Exception e) {
            e.printStackTrace();
            throw new EduException(20001, "导入失败出现异常");
        }
    }

    /**
     * 获取树形列表
     *
     * @return
     */
    @Override
    public List<SubjectNestedVo> nestedList() {
        //最终要的到的数据列表
        ArrayList<SubjectNestedVo> subjectNestedVoArrayList = new ArrayList<>();
        //获取一级分类数据记录
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", "0");
        queryWrapper.orderByAsc("sort", "id");
        List<EduSubject> subjects = baseMapper.selectList(queryWrapper);
        //获取二级分类数据记录
        QueryWrapper<EduSubject> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.ne("parent_id", "0");
        queryWrapper2.orderByAsc("sort", "id");
        List<EduSubject> subSubjects = baseMapper.selectList(queryWrapper2);
        //填充一级分类vo数据
        int count = subjects.size();
        for (int i = 0; i < count; i++) {
            EduSubject subject = subjects.get(i);
            //创建一级类别vo对象
            SubjectNestedVo subjectNestedVo = new SubjectNestedVo();
            BeanUtils.copyProperties(subject, subjectNestedVo);
            subjectNestedVoArrayList.add(subjectNestedVo);
            //填充二级分类vo数据
            ArrayList<SubjectVo> subjectVoArrayList = new ArrayList<>();
            int count2 = subSubjects.size();
            for (int j = 0; j < count2; j++) {
                EduSubject subSubject = subSubjects.get(j);
                if (subject.getId().equals(subSubject.getParentId())) {
                    //创建二级类别vo对象
                    SubjectVo subjectVo = new SubjectVo();
                    BeanUtils.copyProperties(subSubject, subjectVo);
                    subjectVoArrayList.add(subjectVo);
                }
            }
            subjectNestedVo.setChildren(subjectVoArrayList);
        }
        return subjectNestedVoArrayList;
    }

    @Override
    public boolean deleteSubjectById(String id) {
        //判断一级分类下面有没有二级id
        //根据parent_id查询
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<EduSubject> list = baseMapper.selectList(wrapper);
        //判断如果有二级分类
        if (list.size() > 0) {
            for (EduSubject eduSubject : list) {
                baseMapper.deleteById(eduSubject.getId());
            }
            baseMapper.deleteById(id);
            return true;
        } else {
            //进行删除
            int i = baseMapper.deleteById(id);
            if (i > 0) {
                return true;
            }
            return false;
        }
    }

    /**
     * 添加节点
     * @param eduSubject
     * @return
     */
    @Override
    public boolean insertSubject(EduSubject eduSubject) {
        eduSubject.setId(UUID.randomUUID().toString());
        eduSubject.setSort(0);
        int insert = baseMapper.insert(eduSubject);
        return insert>0;
    }

    /**
     * 判断数据库是否存在一级id
     *
     * @param name
     * @return
     */
    private EduSubject existOneSubject(String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        EduSubject eduSubject = baseMapper.selectOne(wrapper);
        return eduSubject;

    }

    /**
     * 判断数据库是否存在二级id
     *
     * @param name
     * @return
     */
    private EduSubject existTwoSubject(String name, String idParent) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", idParent);
        EduSubject eduSubject = baseMapper.selectOne(wrapper);
        return eduSubject;
    }

}
